﻿
using UnityEngine;

/// <summary>
/// Tween the object's position.
/// </summary>

[AddComponentMenu("UGUI/Tween/Tween Position")]
public class UGUITweenPosition : UGUITweener
{
    public override object fromValue { get { return from; } set { from = (Vector3)value; } }
    public override object toValue { get { return to; } set { to = (Vector3)value; } }

    public Vector3 from;
	public Vector3 to;

	[HideInInspector]
	public bool worldSpace = false;

    private bool mCached = false;
    RectTransform mRectTrans;
    Transform mTrans;

    protected override void Start()
    {
        if (delay == 0)
        {
            value = from;
        }
        base.Start();
    }

    void Cache()
    {
        mCached = true;

        mRectTrans = GetComponent<RectTransform>();

        if(mRectTrans == null)
        {
            mTrans = GetComponent<Transform>();
        }
    }

    /// <summary>
    /// Tween's current value.
    /// </summary>
    public Vector3 value
	{
		get
		{
            if (!mCached) { Cache(); }

            if (mRectTrans != null) { return mRectTrans.anchoredPosition3D; }

			return worldSpace ? mTrans.position : mTrans.localPosition;
		}
		set
		{
            if (!mCached) { Cache(); }

            if (mRectTrans != null)
            {
                mRectTrans.anchoredPosition3D = value;
                return;
            }

            if (worldSpace)
            {
                mTrans.position = value;
            }
            else
            {
                mTrans.localPosition = value;
            }
		}
	}

	/// <summary>
	/// Tween the value.
	/// </summary>

	protected override void OnUpdate (float factor, bool isFinished) { value = from * (1f - factor) + to * factor; }

	/// <summary>
	/// Start the tweening operation.
	/// </summary>

	static public UGUITweenPosition Begin (GameObject go, float duration, Vector3 pos)
	{
        UGUITweenPosition comp = UGUITweener.Begin<UGUITweenPosition>(go, duration);
		comp.from = comp.value;
		comp.to = pos;

		if (duration <= 0f)
		{
			comp.Sample(1f, true);
			comp.enabled = false;
		}
		return comp;
	}

	/// <summary>
	/// Start the tweening operation.
	/// </summary>

	static public UGUITweenPosition Begin (GameObject go, float duration, Vector3 pos, bool worldSpace)
	{
        UGUITweenPosition comp = UGUITweener.Begin<UGUITweenPosition>(go, duration);
		comp.worldSpace = worldSpace;
		comp.from = comp.value;
		comp.to = pos;

		if (duration <= 0f)
		{
			comp.Sample(1f, true);
			comp.enabled = false;
		}
		return comp;
	}

	[ContextMenu("Set 'From' to current value")]
	public override void SetStartToCurrentValue () { from = value; }

	[ContextMenu("Set 'To' to current value")]
	public override void SetEndToCurrentValue () { to = value; }

	[ContextMenu("Assume value of 'From'")]
	public void SetCurrentValueToStart () { value = from; }

	[ContextMenu("Assume value of 'To'")]
    public void SetCurrentValueToEnd () { value = to; }
}
